package com.acme.ionio.impl;

import com.acme.ionio.FileCopierClient;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * @author Gregory Sobko
 */
public class FileCopierClientNIO implements FileCopierClient {
    private static Logger logger = Logger.getLogger(FileCopierClientNIO.class);

    @Override
    public void copy(File from, String url, int port) throws IOException {
        try(
            SocketChannel socketChannel = SocketChannel.open();
            FileChannel fileChannel = new FileInputStream(from).getChannel()){
            logger.info("Connecting to server...");
            socketChannel.connect(new InetSocketAddress(url, port));
            logger.info("Connected. Starting transfer.");
            ByteBuffer byteBuffer = ByteBuffer.allocate(8);
            logger.debug("Sending filesize");
            byteBuffer.asLongBuffer().put(fileChannel.size());
            byteBuffer.rewind();
            socketChannel.write(byteBuffer);
            long totalTransferred = 0;
            logger.debug("writing file...");
            while (true){
                totalTransferred += fileChannel.transferTo(totalTransferred, fileChannel.size(), socketChannel);
                if(totalTransferred == fileChannel.size()){
                    break;
                }
            }
            logger.info("Done writing, waiting 4 response.");
            byte[] bytes = new byte[1024];
            socketChannel.read(ByteBuffer.wrap(bytes));
            logger.info(new String(bytes));
        }
    }
}
